package UnitTest;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class StringReverse {

    public static void main(String[] args) {
        //任意深度括号的字符串
        String str2 = "((ui)(oi(ai)(bi)))";
        String result = reverseStr(str2);
        System.out.println(result);
    }

    /**
     * 生成字符串与深度关系的map，实际上每一次得到的map只有括号层最深的key-value 是有效的entry，
     * 得到最深层的子字符串坐标就足够了，反转字符串中的该子字符串并去除括号，然后将处理过的字符串按照上述逻辑递归
     *
     * @param str 原字符串
     */
    public static String reverseStr(String str) {
        int leftCount = 0;
        int rightCount = 0;
        Map<StringEntry, Integer> bracketDeepMap = new HashMap<>();
        //上一个（的索引
        Integer lastLeft = 0;
        for (int i = 0; i < str.length(); i++) {
            String substring = str.substring(i, i + 1);
            if (substring.equals("(")) {
                leftCount++;
                lastLeft = i;
            }
            if (substring.equals(")")) {
                rightCount++;
                int deep = leftCount - rightCount;
                //得到括号中的值
                StringEntry entry = new StringEntry(lastLeft, i);
                //得到值与深度的entry
                bracketDeepMap.put(entry, deep);
            }
        }
        //获得层最深的entry
        Optional<Map.Entry<StringEntry, Integer>> optionalEntry = bracketDeepMap.entrySet().stream().max((entry1, entry2) ->
                entry1.getValue().compareTo(entry2.getValue())
        );
        if (optionalEntry.isPresent()) {
            StringEntry entryKey = optionalEntry.get().getKey();
            String key = str.substring(entryKey.leftIndex, entryKey.rightIndex + 1);
            String reverse = reverse(key.substring(1, key.length() - 1));
            str = str.replace(key, reverse);
            System.out.println(str);
            return reverseStr(str);
        }
        return str;
    }

    /**
     * 反转任意字符串
     *
     * @param originStr 原字符串
     */
    public static String reverse(String originStr) {
        if (originStr == null || originStr.length() <= 1)
            return originStr;
        return reverse(originStr.substring(1)) + originStr.charAt(0);
    }
}

//辅助类 括号子字符串在字符串中的坐标
class StringEntry {
    Integer leftIndex;
    Integer rightIndex;

    public StringEntry(Integer leftIndex, Integer rightIndex) {
        this.leftIndex = leftIndex;
        this.rightIndex = rightIndex;
    }

    public StringEntry() {

    }

    @Override
    public String toString() {
        return "StringEntry{" +
                "leftIndex=" + leftIndex +
                ", rightIndex=" + rightIndex +
                '}';
    }
}
